package com.example.concurrentprogramming8016.blockingqueue;

import java.util.Random;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author liyanhao
 * @Date 2023-01-07 20:55
 * 一个阻塞队列，其中每个插入操作都必须等待另一个线程的相应删除操作，
 * 反之亦然。同步队列没有任何内部容量，甚至没有一个容量
 */
public class SynchronousQueueDemo {
    public static void main(String[] args) {

        SynchronousQueue<Object> synchronousQueue = new SynchronousQueue<>();
        new Thread(() -> {
            for (; ; ) {
                try {
                    synchronousQueue.put(new Random().nextInt() * 100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
        new Thread(() -> {
            for (; ; ) {
                try {
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println(synchronousQueue.take());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();

    }
}
